﻿using System.Collections.Concurrent;
using WeDonekRpc.Helper;

namespace Base.FileGateway.PdfConvert
{
    internal class FilePdfService
    {
        private static readonly ConcurrentDictionary<long, PdfConvertTask> _TaskList = new ConcurrentDictionary<long, PdfConvertTask>();
        private static readonly Timer _ClearTask = new Timer(new TimerCallback(_Clear), null, 60000, 60000);

        private static void _Clear ( object? state )
        {
            if ( _TaskList.IsEmpty )
            {
                return;
            }
            int time = HeartbeatTimeHelper.HeartbeatTime - 30;
            long[] taskId = _TaskList.Where(a => a.Value.IsComplete && a.Value.EndTime <= time).Select(a => a.Key).ToArray();
            if ( !taskId.IsNull() )
            {
                taskId.ForEach(c =>
                {
                    _ = _TaskList.TryRemove(c, out _);
                });
            }
        }
        public static PdfConvertTask CreateTask ( long fileId, FileInfo file )
        {
            if ( !_TaskList.TryGetValue(fileId, out PdfConvertTask task) )
            {
                task = new PdfConvertTask(fileId, file);
                if ( _TaskList.TryAdd(fileId, task) )
                {
                    task.Begin();
                    return task;
                }
                return CreateTask(fileId, file);
            }
            return task;
        }
    }
}
